package token.mobileapp.persistenceactivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import token.mobileapp.TokenActivity;
import token.mobileapp.model.UserInfo;
import token.mobileapp.utils.Constants;

import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * Created by IntelliJ IDEA.
 * UserInfo: AVAVT
 * Date: 7/9/11
 * Time: 8:21 PM
 * To change this template use File | Settings | File Templates.
 */
public class UserInfoPersistence extends TokenActivity {
    private UserInfo userInfo = null;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent thisIntent = getIntent();
        if (thisIntent.getIntExtra("requestCode", Constants.REQUEST_CODE_UNKNOWN) == Constants.REQUEST_CODE_SAVE_USER) {
            userInfo = (UserInfo) thisIntent.getExtras().getSerializable("userInfo");
            saveUserInfo();
        } else if (thisIntent.getIntExtra("requestCode", Constants.REQUEST_CODE_UNKNOWN) == Constants.REQUEST_CODE_LOAD_USER) {
            loadUserInfo();
        } else {
            Intent resultIntent = new Intent();
            resultIntent.putExtra("errMessage", "Invalid request");
            setResult(Activity.RESULT_CANCELED);
            finish();
        }
    }

    private void saveUserInfo() {
        if (userInfo != null) {
            try {
                FileOutputStream fos = openFileOutput(Constants.FILE_NAME, Context.MODE_PRIVATE);
                fos.write((userInfo.getPINCode().toString() + ";").getBytes());
                fos.write((userInfo.getSeed().toString() + ";").getBytes());
                fos.write((userInfo.getEvent().toString() + ";").getBytes());
                fos.write((userInfo.getSecretKey().toString()).getBytes());
                fos.close();
                setResult(Activity.RESULT_OK);
            } catch (Exception ex) {
                Intent resultIntent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("err", ex);
                resultIntent.putExtras(bundle);
                setResult(Activity.RESULT_CANCELED, resultIntent);
            } finally {
                finish();
            }
        } else {
            getApplicationContext().deleteFile(Constants.FILE_NAME);
            setResult(Activity.RESULT_OK);
        }
    }

    private void loadUserInfo() {
        userInfo = new UserInfo();
        try {
            FileInputStream fis = openFileInput(Constants.FILE_NAME);

            int ch;
            StringBuffer fileContent = new StringBuffer("");
            while ((ch = fis.read()) != Constants.FILE_SEPARATOR)
                fileContent.append((char) ch);
            String[] userData = new String(fileContent).split(";");

            switch (userData.length) {
                case 4:
                    userInfo.setSecretKey(userData[3]);
                case 3:
                    userInfo.setEvent(userData[2]);
                case 2:
                    userInfo.setSeed(userData[1]);
                case 1:
                    userInfo.setPINCode(userData[0]);
                    break;
                default:
                    break;
            }

            fis.close();
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putSerializable("userInfo", userInfo);
            resultIntent.putExtras(bundle);

            setResult(Activity.RESULT_OK, resultIntent);
        } catch (Exception ex) {
            Intent resultIntent = new Intent();
            Bundle bundle = new Bundle();
            bundle.putSerializable("err", ex);
            resultIntent.putExtras(bundle);
            setResult(Activity.RESULT_CANCELED, resultIntent);
        } finally {
            finish();
        }
    }
}
